/*
* @Author: An
* @Date:   2017-07-09 16:03:46
* @Last Modified by:   An
* @Last Modified time: 2017-07-09 16:28:39
*/

'use strict';

require('page/common/header/index.js');
require('page/common/nav/index.js');
require('./index.css');
var _xj 			= require('util/xj.js');
var _user 			= require('service/user-service.js');
var navSide 		= require('page/common/nav-side/index.js');

// page逻辑
var page = {
	init : function() {
		this.onLoad();
		this.bindEvent();
	},
	onLoad : function() {
		// 初始化左侧菜单
		navSide.init({
			name : 'user-center'
		});
	},
	bindEvent : function() {
		var _this = this;
		// 点击提交按钮后的动作
		$(document).on('click', '.btn-submit', function() {
			var userInfo = {
				password  	 	: $.trim($('#password').val()),
				passwordNew		: $.trim($('#password-new').val()),
				passwordConfirm	: $.trim($('#password-confirm').val())
			},
			validateResult = _this.validateForm(userInfo);
			if (validateResult.status) {
				_user.updatePassword({
					passwordOld : userInfo.password,
					passwordNew : userInfo.passwordNew
				}, function(res, msg) {
					_xj.successTips(msg);
					window.location.href = './user-login.html';
				}, function(errMsg) {
					_xj.errorTips(errMsg);	
				});
			} else {
				_xj.errorTips(validateResult.msg);
			}
		});
	},
	validateForm : function(formData) {
		var result = {
			status 	: false,
			msg 	: ''
		};
		// 验证原密码是否为空
        if(!_xj.validate(formData.password, 'require')){
            result.msg = '原密码不能为空';
            return result;
        }
        // 验证新密码长度
        if(!formData.passwordNew || formData.passwordNew.length < 6){
            result.msg = '密码长度不得少于6位';
            return result;
        }
        // 验证两次输入的密码是否一致
        if(formData.passwordNew !== formData.passwordConfirm){
            result.msg = '两次输入的密码不一致';
            return result;
        }
		// 通过验证，返回正确提示
		result.status 	= true;
		result.msg 		= '校验通过';
		return result;
	}
};

$(function() {
	page.init();
});